package util.thread.threadpool;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 缓存线程池，可以灵活收回空闲线程，若无可回收则创建新的。默认为1分钟。
 *
 * @author: Lidong
 * @time: 2020/8/6 21:32
 **/
public class CachedThreadPoolTest {

    private static final Logger logger = LoggerFactory.getLogger(CachedThreadPoolTest.class);


    private void useCachedThreadPool(int y) throws Exception {
        ExecutorService executor = Executors.newCachedThreadPool();
        for (int i = 0; i < y; i++) {
            int index = i;
            Thread.sleep(4000);
            executor.execute(() -> logger.info("{}  {}", Thread.currentThread().getName(), index));
        }
    }

    @Test
    public void test() {
        try {
            useCachedThreadPool(5);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

}
